import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
import type { AppDispatch } from "../store";
import loginApi from "../../../apis/loginApi";
import type { LoginByAccountDto } from "../../../types/login-api";
import userInfoMgr from "../../cookieMgr/userInfoMgr";
import tokenMgr from "../../cookieMgr/tokenMgr";

// 为 slice state 定义一个类型
interface AuthState {
  isPassed: boolean;
  userInfo: any;
  token: string;
}

// 使用该类型定义初始 state
const initialState = {
  isPassed: false,
  userInfo: {},
  token: "",
} as AuthState;

export const authSlice = createSlice({
  name: "auth",
  // `createSlice` 将从 `initialState` 参数推断 state 类型
  initialState,
  reducers: {
    pass: (state) => {
      state.isPassed = true;
    },
    setUserInfo: (state, action: PayloadAction<any>) => {
      state.userInfo = action.payload;
      userInfoMgr.setUserInfo(state.userInfo);
    },
    // 使用 PayloadAction 类型声明 `action.payload` 的内容
    setToken: (state, action: PayloadAction<string>) => {
      state.token = action.payload;
      tokenMgr.setToken(state.token);
    },
  },
});

const { pass, setUserInfo, setToken } = authSlice.actions;

// 实现业务逻辑

// 登录
export const login = (data: LoginByAccountDto) => {
  return async (appDispatch: AppDispatch) => {
    const res = await loginApi.loginByAccount(data);
    if (res.status >= 0) {
      appDispatch(setToken(res.data));
      location.href = "/";
    }
    return res;
  };
};

// 检查登录
export const checkLogin = () => {
  return async (appDispatch: AppDispatch) => {
    const res = await loginApi.checkLogin();
    if (res.status >= 0) {
      appDispatch(setUserInfo(res.data));
      appDispatch(pass());
    } else {
      location.href = "/login";
    }
    return res;
  };
};

export default authSlice.reducer;
